import hashlib
import calendar
import time


def for_else():
    # for --else
    for i in range(0, 5):
        print(i)
    else:
        print(i, 'This is else')
    for i in range(0, 5):
        if i > 2:
            print(i)
    else:
        print(i, 'This is else')


# 三元表达式
def ternary_operator(x, y):
    if y > x:
        print('max:', y)
    else:
        print('max:', x)
    print('max is:', x if x > y else y)


def with_as():
    fp = open(r'C:\Users\test\RGBmessage.txt', 'r')
    try:
        contents = fp.read()
    finally:
        fp.close()

    print('*'*15)
    with open(r'C:\Users\test\RGBmessage.txt', 'r')as f:
        contents = f.read()


# 列表推导式：推导式不仅支持列表，也支持字典、集合、元组等对象
def list_derivation():
    a = [1, 2, 3, 4, 5]
    result = list()
    for i in a:
        result.append(i*i)
    print(result)
    print('*'*15)
    result = [i*i for i in a]
    print(result)


# 列表索引
def list_index():
    a = [1, 2, 3, 4, 5, 6, 7, 8]
    print(a[2:4])
    print(a[3:])
    print(a[:])
    print(a[::2])
    print(a[1::2])
    print(a[-1])
    print(a[1:-1])
    print(a[::-1])
    b = ['a', 'b']
    a[2:2] = b
    print(a)
    a[3:6] = b
    print(a)


# lambda函数
def lambda_fun():
    a = (lambda x, y: x+y)(12, 38)  # 因为匿名函数没有名字，使用的时候要用括号把它包起来
    print(a)


# yield 以及生成器和迭代器
def yield_test(x):
    a = [1, 2, 3, 4]
    a_iter = iter(a)  # 迭代函数 iter，用于生成迭代器
    for i in a_iter:
        print(i, end=" ")
    print()

    # yield 则是用于构造生成器的
    result = list()
    for i in range(5):
        result.append(i**2)
    print(result)
    for i in range(x):
        yield(pow(i, 2))


def print_fun(a):
    for i in a:
        print(i, end=" ")


# 装饰器
# timer() 是定义的装饰器函数，使用@把它附加在任何一个函数（比如do_something）定义之前，就等于把新定义的函数，当成了装饰器函数的输入参数。运行 do_something() 函数，可以理解为执行了timer(do_something) 。
def timer(func):
    def wrapper(*args, **kwargs):
        t0 = time.time()
        func(*args, **kwargs)
        t1 = time.time()
        print('耗时：%0.3f' % (t1-t0))
    return wrapper


@timer
def do_something(delay):
    print('开始')
    time.sleep(delay)
    print('结束')


# 断言assert
# 所谓断言，就是声明表达式的布尔值必须为真的判定，否则将触发 AssertionError 异常。严格来讲，assert是调试手段，不宜使用在生产环境中，但这不影响我们用断言来实现一些特定功能，比如，输入参数的格式、类型验证等
def i_want_to_sleep(delay):
    assert(isinstance(delay, (int, float))), '函数参数必须为整数或浮点数'
    print('开始睡觉')
    time.sleep(delay)
    print('睡醒了')


# 乘法表
def mul():
    for i in range(1, 10):
        for j in range(1, i+1):
            print(f'{i}*{j}={i*j}', end=' ')
        print('')
    i = 1
    while i < 10:
        j = 1
        while j <= i:
            print('%d*%d=%2d' % (j, i, j*i), end=' ')
            j += 1
        print('')
        i += 1
    for i in range(1, 10):
        for j in range(1, 10-i):
            print(end='       ')
        for k in range(1, i+1):
            print('%d*%d=%2d' % (k, i, k*i), end=' ')
        print('')


if __name__ == '__main__':
    for_else()
    ternary_operator(12, 90)
    with_as()
    list_derivation()
    list_index()
    lambda_fun()
    a = yield_test(5)
    print_fun(a)
    do_something(3)
    i_want_to_sleep(2)
    mul()
    # 运用MD5算法
    md5 = hashlib.md5()
    data = 'Hello World'
    md5.update(data.encode('utf-8'))
    print(md5.hexdigest())

    # 运用SHA1算法
    sha1 = hashlib.sha1()
    data = 'Hello World'
    sha1.update(data.encode('utf-8'))
    print(sha1.hexdigest())

    # calendar 模块
    print(calendar.month(2021, 10))
    print(calendar.calendar(2021))
